import type { RouteRecordRaw } from 'vue-router';
import { useUserStore, useAppStore } from '@/store';
import { getToken } from '@/utils/auth';

import router from '../index';
import { DYNMIC_ROUTES } from '../index';

// 获取到views下的所有vue文件
const modules = import.meta.glob('@/views/**/*.vue')

// 给router对象插入路由
const addRoute = async (serverMenus: RouteRecordRaw[]) => {
    return new Promise<void>((resolve) => {
        serverMenus.forEach(item => {
            if (router.hasRoute(item.name!)) {
                return;
            }
            if (item.path.indexOf('http') !== -1) {
                return;
            }
            router.addRoute(item)
        });
        resolve()
    })
}

// 最终执行的方法
const addUserRoutes = async () => {
    const appStore = useAppStore();
    const userStore = useUserStore();
    // 针对来自服务端的菜单配置进行处理
    let serverMenus: RouteRecordRaw[] = [];
    // 如果没有token信息 不注入路由
    if (!getToken()) {
        return;
    }
    if (appStore.menuFromServer) {
        // 当缓存中没有菜单信息
        if (!appStore.appAsyncMenus.length) {
            await appStore.fetchServerMenuConfig();
        }
        serverMenus = appStore.appAsyncMenus;
    } else {
        serverMenus = DYNMIC_ROUTES;
    }
    await addRoute(serverMenus)
    appStore.setAddRoute(true)
}

export default addUserRoutes